package com.mao.interview.string;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.naming.spi.DirStateFactory.Result;

/**
 * 计算一个字符串中 出现次数最多的字母，如果有相同次数的，也一起打印出来
 */
public class MaxCountCharParser {

	private static class Node {

		Node(Character ch, Integer count) {
			this.ch = ch;
			this.count = count;
		}

		Character ch;
		Integer count;
	}

	private HashMap<Character, Integer> map = new HashMap<>();

	private ArrayList<Node> resultList = new ArrayList<>();

	private void parseString(String str) {
		final String s = str;
		map.clear();
		for (int i = 0; i < str.length(); i++) {
			Character cha = s.charAt(i);
			Integer count = map.get(cha);
			if (count == null) {
				count = 0;
			}
			count++;
			map.put(cha, count);
		}

	}

	private void doSort(HashMap<Character, Integer> map) {
		resultList.clear();
		Set<Character> keySet = map.keySet();
		Iterator<Character> iterator = keySet.iterator();
		int max;
		Character ch = null;
		Integer count = null;
		while (iterator.hasNext()) {
			if (resultList.size() == 0) {
				max = 0;
			} else {
				max = resultList.get(0).count;
			}
			ch = iterator.next();
			count = map.get(ch);
			if (max > count) {
				continue;
			} else if (max == count) {

			} else {
				resultList.clear();
			}
			resultList.add(new Node(ch, count));
		}
	}

	public synchronized HashMap<Character, Integer> getMaxCountCharacter(String str) {

		parseString(str);

		doSort(map);

		HashMap<Character, Integer> outer = new HashMap<>();

		for (int i = 0; i < resultList.size(); i++) {
			outer.put(resultList.get(i).ch, resultList.get(i).count);
		}

		return outer;
	}

	public static void main(String[] args) {

		String data = "aavzcadfdsfsdhshgWasdfasdfddaaa";

		String test1 = "aaaDDbbbbccccDDDDDD";

		MaxCountCharParser parser = new MaxCountCharParser();

		Map<Character, Integer> map = parser.getMaxCountCharacter(test1);
		for (Character ch : map.keySet()) {
			System.out.println("char = " + ch + " ,count = " + map.get(ch));
		}

	}
}
